package com.example.bookstore.taglib;

import javax.el.ValueExpression;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.webapp.ValidatorELTag;
import javax.servlet.jsp.JspException;

import com.example.bookstore.validators.FormatValidator;

public class FormatValidatorTag extends ValidatorELTag {

	private static final long serialVersionUID = 1L;

	private static String validatorID = null;
	protected ValueExpression formatPatterns = null;

	public FormatValidatorTag() {
		super();

		if (validatorID == null) {
			validatorID = "FormatValidator";
		}
	}

	public void setValidatorID(String validatorID) {
		FormatValidatorTag.validatorID = validatorID;
	} // END setValidatorId
		// Attribute Instance Variables

	//
	// Class methods
	//
	public void setFormatPatterns(ValueExpression formatPatterns) {
		this.formatPatterns = formatPatterns;
	}

	@Override
	protected Validator createValidator() throws JspException {
		FacesContext facesContext = FacesContext.getCurrentInstance();
		FormatValidator result = null;

		if (validatorID != null) {
			result = (FormatValidator) facesContext.getApplication()
					.createValidator(validatorID);
		}

		String patterns = null;

		if (formatPatterns != null) {
			if (!formatPatterns.isLiteralText()) {
				patterns = (String) formatPatterns.getValue(facesContext
						.getELContext());
			} else {
				patterns = formatPatterns.getExpressionString();
			}
		}

		result.setFormatPatterns(patterns);

		return result;
	}

}
